//
//  LoginVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/6/26.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "LoginVC.h"

#import "TeacherHomeVC.h"
#import "HNSNHomePageVC.h"
#import "OrdinaryHomeVC.h"
#import "NotesTeacherVC.h"
#import "LoginHistoryView.h"
#import "FirstAuditingVC.h"
#import "ForgotPasswordVC.h"
#import "SuperManagerVC.h"
#import "SalesManVC.h"
#import "HNTabBarController.h"


@interface LoginVC ()
{
    IBOutlet UITextField *_Phone;
    IBOutlet UITextField *_Password;

    /** 专门用于超级管理员的信息处理，其他的无视 */
    NSDictionary *_dict;
    
    UIViewController *_tempVC;
}
/**
 用来做登录历史存放地的
 */
@property (nonatomic, strong) NSMutableArray *DataArr;


@end

@implementation LoginVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    //隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    


}


- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
 
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    //显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}



- (void)viewDidLoad
{
    [super viewDidLoad];


    //取出临时保存的登录信息
    NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
    _Phone.text     = [UserDefaults objectForKey:@"Phone"];
    _Password.text  = [UserDefaults objectForKey:@"Password"];

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"loginState"] == YES) {
        
        [self GoVC:[[AccountTool shareAccountTool].currentAccount.rolecode integerValue]];
    }
}

#pragma mark - 网络请求
/**
 开始进行登录的网络请求
 */
- (void)RefreshDataWithLogin:(NSString *)Phone Password:(NSString *)Password
{
    [HUD showHUD];
    NSDictionary *Params = @{
                             @"action"        :@"login3",
                             @"phone"         :Phone,
                             @"password"      :Password
                             };

    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:NO Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000])
        {

            // 只有超级管理员才得上，其他无视
            _dict = Obj;
            // Auth加密
            [self authEncryptWithUserName:Phone password:Password Obj:Obj];
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }

    } Fail:^(NSError *Error) {

        [HUD showError:NetErr];
    }];
}



/**
 auth加密
 */
- (void)authEncryptWithUserName:(NSString *)userName password:(NSString *)password Obj:(id)Obj
{

    [HUD showHUD];
    //将用户名与密码拼接
    NSString *source = [NSString stringWithFormat:@"%@:%@",userName,password];
    NSDictionary *Params = @{
                             @"action"  :@"genAuthCode",
                             @"source"  :source,
                             @"key"     :@"keykeyString"
                             };
    [NetManager Get:LLBaseURLs(@"auth.do") Auth:NO Params:Params Success:^(id responseObj) {

        // auth加密成功
        if ([responseObj[@"code"] isEqualToNumber:@1000])
        {
            NSDictionary *dict = [Obj valueForKey:@"t"];
            //保存账号信息
            Account *account = [[Account alloc] init];
            NSString *uid           = [[dict objectForKey:@"uid"]stringValue];
            NSString *userName      = [dict objectForKey:@"username"];
            NSString *auth          = responseObj[@"t"][@"authCode"];
            NSString *rolecode      = dict[@"rolecode"];
            NSString *avatar        = dict[@"avatar"];
            NSString *petName       = dict[@"petName"];

            [self authEncryptWithUserNames:uid];
            
            NSString *oid = @"";
            NSString *websiteName = @"";
            NSString *picture = @"";
            BOOL isReinforce = NO;
            if ([rolecode integerValue] == 9 || [rolecode integerValue] == 15 || [rolecode integerValue] == 31) {

                // 如果帐户的信息不完整的话是不会有机构实体信息的

                NSDictionary *xx = dict[@"organizationInfo"];
                if (![xx isKindOfClass:[NSNull class]]) {

                    oid           = [xx[@"id"] isKindOfClass:[NSNull class]] ? @"":xx[@"id"];
                    websiteName   = [xx[@"websiteName"] isKindOfClass:[NSNull class]] ? @"":xx[@"websiteName"];
                    picture       = [xx[@"picture"] isKindOfClass:[NSNull class]] ? @"":xx[@"picture"];
                    isReinforce   = [xx[@"isReinforce"] isEqualToNumber:@1] ? YES:NO;
                }
            }

            account.uid         = uid;
            account.username    = userName;
            account.rolecode    = rolecode;
            account.avatar      = avatar;
            account.petName     = petName;
            account.authCode    = auth;
            account.password    = password;
            account.websiteName = websiteName;
            account.picture     = picture;
            account.oid         = oid;
            account.isReinforce = isReinforce;
            [[AccountTool shareAccountTool] saveAccount:account];


            //临时保存帐户信息
            NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
            [UserDefaults setObject:userName forKey:@"Phone"];
            [UserDefaults setObject:password forKey:@"Password"];
            [UserDefaults setValue:oid forKey:@"id"];
            [UserDefaults setBool:YES forKey:@"loginState"];
            [UserDefaults synchronize];

            // 保存账户和密码到历史登录信息处
            [self MgrSaveAccountPasswordToHost_Account:userName Password:password];

            // 设置极光推送的tap值
            AppDelegate.SetupJPUSH_Tag (dict[@"uid"]);

            // 根据rolecode跳转相应界面
            [self GoVC:[rolecode integerValue]];

        }
        else
        {
            [HUD showError:responseObj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        [HUD showError:NetErr];
    }];
}

#pragma mark - 点击事件
/**
 点击事件：登录
 */
- (IBAction)BeginLogin:(UIButton *)sender
{
    // 开始进行登录
    [self MgrLogin:_Phone.text Password:_Password.text];
}



/**
 点击事件:打开登录的历史记录
 */
- (IBAction)OpenLoginHistory:(UIButton *)sender
{
    // 开始打开历史记录
    [self MgrOpenHistoryView:sender];
}


- (IBAction)ForgotPassword:(UIButton *)sender {

    ForgotPasswordVC *VC = [[ForgotPasswordVC alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 处理方法
/**
 开始进行登录
 */
- (void)MgrLogin:(NSString *)Phone Password:(NSString *)Password
{
    if (Phone.length <= 0 || Password.length <= 0)
    {
        [HUD showError:@"请完善登录信息"];
        return;
    }

    // 开始登录
    [self RefreshDataWithLogin:Phone Password:Password];
}



-(void)authEncryptWithUserNames:(NSString *)uid{
    
    NSString *source = [NSString stringWithFormat:@"%@",uid];
    //uid   285
    NSString *url = [NSString stringWithFormat:@"auth.do?action=genAuthCode&source=%@&key=keykeyString",source];
    
    
    NSLog(@"%@",LLBaseURLs(url));
    
    [NetManager Get:LLBaseURLs(url) Auth:NO Params:nil Success:^(id Obj) {
        NSDictionary *dict = [Obj objectForKey:@"t"];
        
        NSString *auth = [dict objectForKey:@"authCode"];

        //保存auth信息
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:auth forKey:@"authCode"];
        [defaults synchronize];
        
    } Fail:^(NSError *Error) {
        
        
        
        NSLog(@"%@",Error);
        
    }];
    

    
}



/**
 根据rolecode跳转相应界面
 */
- (void)GoVC:(NSInteger)Index
{
    //15为sn机构和9为普通机构
    //2为机构老师
    if (Index == 2)
    {
        TeacherHomeVC *VC = [[TeacherHomeVC alloc] init];
        [self PresentVC:VC];
    }
    // 15为SN机构
    else if (Index == 15)
    {
        HNSNHomePageVC *VC = [[HNSNHomePageVC alloc] init];
        [self PresentVC:VC];
        
    }
    // 9为普通机构
    else if (Index == 9)
    {
        HNTabBarController *VC = [HNTabBarController TabBarController];
        [self AnimaitePushWithVC:VC];
    }
    // 13为初审账号 14终审账户
    else if (Index == 13 || Index == 14)
    {
        FirstAuditingVC *VC = [[FirstAuditingVC alloc] init];
        [self PresentVC:VC];
        
    }
    // 20为批注老师
    else if (Index == 20)
    {
        NotesTeacherVC *VC = [[NotesTeacherVC alloc] init];
        [self PresentVC:VC];
        
    }
    // 超级管理员
    else if (Index == 31)
    {
        SuperManagerVC *VC = [[SuperManagerVC alloc] init];
        VC.dict = _dict;
        [self PresentVC:VC];
        
    }
    else if (Index == 33) {
        
        SalesManVC *VC = [[SalesManVC alloc] init];
       
        [self PresentVC:VC];
        
    }
    else
    {
        [HUD showError:@"抱歉!您的帐户无法登录该管理系统"];
    }
}

/**
 处理打开历史记录
 */
- (void)MgrOpenHistoryView:(UIButton *)Button
{
    // 如果没有登录历史就做不处理
    if (self.DataArr == nil)
    {
        return;
    }

    // 有登录记录
    [LoginHistoryView LoginHistoryView_DataArr:self.DataArr Select:^(NSDictionary *Dict) {

        // 选择了哪个账号 @{@"Account":@"",@"Password":@""}
        _Phone.text = Dict[@"Account"];
        _Password.text = Dict[@"Password"];
    }];
}


/**
 处理保存账户密码信息到本地
 */
- (void)MgrSaveAccountPasswordToHost_Account:(NSString *)Account Password:(NSString *)Password
{
    NSMutableArray *TempDataArr = [NSMutableArray arrayWithContentsOfFile:[CachePath stringByAppendingPathComponent:AccountFile]];
    if (TempDataArr == nil)
    {
        TempDataArr = [NSMutableArray array];
    }
    // 检查历史账户里是否有一样用户
    NSMutableArray *Arr = [NSMutableArray array];
    [TempDataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 取值
        NSDictionary *Dict = (NSDictionary *)obj;
        // 开始检测

        if ([Account isEqualToString:Dict[@"Account"]])
        {
            [Arr addObject:Dict];
            // 找到相同项之后就停止循环
            *stop = YES;
        }
    }];
    // 删除这个Dict
    [TempDataArr removeObjectsInArray:Arr];
    // 删除后将新的账户密码写进去
    [TempDataArr addObject:@{@"Account":Account,@"Password":Password}];
    // 写入缓存
    [TempDataArr writeToFile:[CachePath stringByAppendingPathComponent:AccountFile] atomically:NO];
}

- (void)MgrForgotPassword {

    ForgotPasswordVC *VC = [[ForgotPasswordVC alloc] init];
    [self.navigationController presentViewController:VC animated:YES completion:^{
        [VC.navigationController setNavigationBarHidden:YES animated:YES];
    }];
}


- (void)AnimaitePushWithVC:(UIViewController *)VC {
    
    CATransition  *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromRight;
    //设置运动速度变化
    transition.timingFunction = UIViewAnimationOptionPreferredFramesPerSecondDefault;
    [self.view.superview.layer addAnimation:transition forKey:@"animation"];
    [self presentViewController:VC animated:NO completion:nil];
}


- (void)PresentVC:(UIViewController *)VC {
    
    _tempVC = VC;
    XDNavigationController *NV2 = [[XDNavigationController alloc] initWithRootViewController:VC];
    VC.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(XXXXPop) image:@"nav_icon_back_default" highImage:@"nav_icon_back_default"];
    [self AnimaitePushWithVC:NV2];
}

- (void)XXXXPop {
    
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"loginState"];
    //    // 清除推送tag
    AppDelegate.DeleteJPUSH_Tag();
    [_tempVC dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    return [NSMutableArray arrayWithContentsOfFile:[CachePath stringByAppendingPathComponent:AccountFile]];
}


@end
